#!/usr/bin/env ruby

########################################################################
# convert ChangeLog to google code wiki
# muquit@muquit.com Mar-17-2013 
########################################################################
class ChangeLogToWiki
  ME = $0
  ME_SHORT = File.basename(ME)
  def initialize
    $stdout.sync = true
    @url = "https://mailsend.googlecode.com/svn/trunk/changelog2wiki.rb"
  end

  def kprint(line)
    Kernel.print line
  end

  def escape_html(line)
    line = line.gsub(/</,"`<")
    line = line.gsub(/>/,">`")
    return line
  end

  def doit
    file = ''
    file = "ChangeLog" if File.exists?("ChangeLog")
    file = "ChangeLog.txt" if File.exists?("ChangeLog.txt")
    f = File.open(file)
    list_found = false
    project=File.basename(Dir.pwd)
    puts <<EOD
#summary ChangeLog of #{project}
#sidebar Toc
#labels Featured
<wiki:toc />
EOD
    while ((line = f.gets))
      line.chomp!
      line.strip!
      if line =~ /^=/
        puts line
        next
      end
      if line =~ /^[0-9]+\..*$/
        puts "=#{line}="
        next
      end
      if line =~ /^-/
        line.gsub!(/^-/,"")
        line = line.gsub("/\n","")
        line = escape_html(line)
        if list_found
          kprint "\n  *#{line}"
        else
          kprint "  *#{line}"
        end
        list_found = true
      else
        if line =~ /^\([a-zA-Z]+-[0-9]+-[0-9]+\)$/
          puts "\n_#{line}_"
          list_found = false
        else
          next if line.length == 0
          line = line.gsub("/\n","")
          line = escape_html(line)
          if list_found
            kprint " #{line}"
          else
            puts " #{line}"
          end
        end
      end
    end
  t = Time.new
  puts <<EOD
----
This wiki is auto generated by [#{@url} #{ME_SHORT}] on #{t}.
EOD

  end
end

if __FILE__ == $0
  ChangeLogToWiki.new.doit
end
